#include<iostream>
#include<unistd.h>
#include<fcntl.h>
#include<cstdio>
#include<cstring>
using namespace std;

//非阻塞式
void SetNonBlock(int fd){
    int fl = fcntl(fd,F_GETFL);
    if(fl < 0){
        perror("fcntl");
        return;
    }
    fcntl(fd,F_SETFL,fl | O_NONBLOCK);
    cout<< "set "<<fd<< "nonblock done"<<endl;
}

int main(){
    char buffer[1024];
    while(true){
        printf("place Enter#");
        fflush(stdout);
        ssize_t n = read(0,buffer,sizeof(buffer) -1);
        if(n > 0){
            buffer[n - 1] = 0;
            printf("echo: %s\n",buffer);
        }
        else if(n == 0){
            printf("read done");
            break;
        }
        else{
            //若为非阻塞，fd中没有数据，返回值会以出错形式返回
            // 通过errno 判断是否真的出错
            if(errno == EWOULDBLOCK){
                cout<<" 0 fd,try again"<<endl;
                sleep(1);
            }            
            else{
                 cerr<< "read error, n = "<<n<<"errno code:"<< errno
            <<", errno str: "<<strerror(errno)<<endl;
                break;
            }
        }
    }
    return 0;
}